import { ActionType, ProTable } from '@ant-design/pro-table'
import { useAxiosWebPost, useLocalStorage, useModel, useModal, useModalForm } from '@sker/sdk'
import { Button, Card, DatePicker, Modal, Popconfirm } from 'antd'
import { UserSelector } from '@sker/ui'
import { FjCompanyEntity } from "@sker/model"
import { PlusOutlined } from '@ant-design/icons'
import { BetaSchemaForm } from '@ant-design/pro-components'
import { useRef } from 'react'
import { FjCompanyUserList } from './company-user-list';

const toCid = (cid: number, length: number) => {
    return (Array(length).join('0') + cid).slice(-length);
}
export const FjCompanyList: React.FC<{}> = ({ }) => {
    const fjCompany = useModel(FjCompanyEntity)
    const { fetch: fetchNextCid } = useAxiosWebPost('imeepos/core/rest/nextval')
    const { fetch: add } = useAxiosWebPost('fj/core/company/add')
    const { fetch: edit } = useAxiosWebPost('fj/core/company/edit')
    const { fetch: del } = useAxiosWebPost('fj/core/company/del')

    const actionRef = useRef<ActionType>()
    const localStorage = useLocalStorage('COMPANY_CID')
    const { modalProps, formProps, setOpen, form, record } = useModalForm({
        title: '新增企业',
        columns: async (record) => {
            if (!record) {
                let nextCid = record?.cid || localStorage.get()
                if (!nextCid) {
                    nextCid = await fetchNextCid({ field: 'fj_company_cid' })
                    localStorage.set(nextCid)
                }
                form.setFieldsValue({
                    status: '1',
                    username: `G${toCid(nextCid, 4)}`,
                    cid: nextCid,
                });
            }
            return [
                {
                    dataIndex: 'id',
                    formItemProps: {
                        hidden: true
                    }
                },
                {
                    dataIndex: 'cid',
                    formItemProps: {
                        hidden: true
                    }
                },
                {
                    title: '企业账号',
                    dataIndex: 'username',
                    fieldProps: {
                        placeholder: '请输入企业账号',
                        disabled: true
                    },
                    formItemProps: {
                        rules: [{ required: true, message: '企业账号必填' }],
                    }
                },
                {
                    title: '企业名称',
                    dataIndex: 'title',
                    fieldProps: {
                        placeholder: '请输入企业名称',
                        autoComplete: 'new-password'
                    },
                    formItemProps: {
                        rules: [{ required: true, message: '企业名称必填' }]
                    }
                },
                {
                    title: '账号密码',
                    valueType: 'password',
                    dataIndex: 'password',
                    fieldProps: {
                        placeholder: '请输入账号密码',
                        autoComplete: 'new-password'
                    },
                    formItemProps: {
                        rules: [{ required: true, message: '账号密码必填' }]
                    }
                },
                {
                    title: '账号状态',
                    dataIndex: 'status',
                    valueType: 'select',
                    convertValue: (val: any) => `${val}`,
                    valueEnum: {
                        0: { text: '禁用' },
                        1: { text: '启用' }
                    },
                    fieldProps: {
                        placeholder: '请选择账号状态'
                    },
                }
            ]
        },
        onFinish: async (values) => {
            values.status = `${values.status}`
            if (!values.id) {
                await add(values)
            } else {
                await edit(values)
            }
            localStorage.remove();
            setOpen(false)
            actionRef.current?.reload();
        }
    })
    const { props: companyMemberProps, setOpen: setCompanyMemberModal, extra } = useModal('查看企业子账号')
    return <Card extra={<Button icon={<PlusOutlined />} type={'primary'} onClick={e => { 
        setOpen(true)
     }}>新增企业</Button>}>
        <Modal {...modalProps}>
            <BetaSchemaForm {...formProps} />
        </Modal>
        <Modal {...companyMemberProps} width={'800px'}>
            <FjCompanyUserList id={extra?.id} />
        </Modal>
        <ProTable
            search={false}
            toolBarRender={false}
            rowKey={(record) => record.id}
            actionRef={actionRef}
            request={async (params, sort, filter) => {
                return fjCompany.find(
                    ['title', 'status', 'create_date', 'id', 'cid', 'count', { user: ['username'], creater: ['username', 'realname'] }],
                    [],
                    [],
                    { current: params.current, pageSize: params.pageSize }
                )
            }} columns={[{
                title: '企业账号',
                dataIndex: ['user', 'username'],
            }, {
                title: '企业名称',
                dataIndex: 'title'
            }, {
                title: '账号状态',
                dataIndex: 'status',
                sorter: true,
                valueEnum: {
                    0: '禁用',
                    1: '启用'
                }
            }, {
                title: '企业子账号数量',
                hideInSearch: true,
                renderText: (_, record) => {
                    return <Button size={'small'} type={'link'} onClick={e => {
                        setCompanyMemberModal(true, record)
                    }}>{record.count || '0'}</Button>
                }
            }, {
                title: '创建日期',
                dataIndex: 'create_date',
                valueType: 'date',
                sorter: true,
                renderFormItem: () => {
                    return <DatePicker.RangePicker />
                }
            }, {
                title: '创建人',
                sorter: true,
                fieldProps: {
                    placeholder: '请选择创建人'
                },
                renderText: (_, record) => {
                    return <>{record.creater?.realname || record.creater?.username}</>
                },
                renderFormItem: () => {
                    return <UserSelector placeholder={'请选择创建人'} />
                }
            }, {
                title: '操作',
                align: 'right',
                renderText(text, record, index, action) {
                    return <>
                        <Button size={'small'} type={'link'} onClick={e => {
                            setOpen(true, { username: record.user.username, cid: record.cid, id: record.id, title: record.title, status: record.status })
                        }}>编辑</Button>
                        <Popconfirm onConfirm={async e => {
                            await del({ id: record.id })
                            await actionRef.current?.reload();
                        }} title={'此操作不可逆!您确定要执行此操作吗？'} description={'删除后无法恢复，请慎重操作！！'}>
                            <Button size={'small'} type={'link'} danger>删除</Button>
                        </Popconfirm>
                    </>
                },
            }]} />
    </Card>
}
